import { createRouter, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/stores/user'

// 医疗系统门户网站路由
const portalRoutes = [
  {
    path: '/portal',
    component: () => import('@/views/portal/Layout.vue'),
    children: [
      {
        path: '',
        name: 'Portal',
        component: () => import('@/views/portal/Home.vue'),
        meta: { title: '首页' }
      },
      {
        path: 'departments',
        name: 'Departments',
        component: () => import('@/views/portal/Departments.vue'),
        meta: { title: '科室导航' }
      },
      {
        path: 'department/:id',
        name: 'DepartmentDetail',
        component: () => import('@/views/portal/DepartmentDetail.vue'),
        meta: { title: '科室详情' }
      },
      {
        path: 'experts',
        name: 'Experts',
        component: () => import('@/views/portal/Experts.vue'),
        meta: { title: '专家团队' }
      },
      {
        path: 'expert/:id',
        name: 'ExpertDetail',
        component: () => import('@/views/portal/ExpertDetail.vue'),
        meta: { title: '专家详情' }
      },
      {
        path: 'guide',
        name: 'Guide',
        component: () => import('@/views/portal/Guide.vue'),
        meta: { title: '就医指南' }
      },
      {
        path: 'news',
        name: 'News',
        component: () => import('@/views/portal/News.vue'),
        meta: { title: '系统动态' }
      },
      {
        path: 'news/:id',
        name: 'NewsDetail',
        component: () => import('@/views/portal/NewsDetail.vue'),
        meta: { title: '新闻详情' }
      },
      {
        path: 'about',
        name: 'About',
        component: () => import('@/views/portal/About.vue'),
        meta: { title: '关于系统' }
      },
      {
        path: 'login',
        name: 'PortalLogin',
        component: () => import('@/views/portal/Login.vue'),
        meta: { title: '用户登录' }
      },
      {
        path: 'register',
        name: 'PortalRegister',
        component: () => import('@/views/portal/Register.vue'),
        meta: { title: '用户注册' }
      },
      // AI咨询页面
      {
        path: 'ai-consultation',
        name: 'AIConsultation',
        component: () => import('@/views/portal/AIConsultation.vue'),
        meta: { title: 'AI医疗咨询' }
      },
      // 医疗知识图谱页面
      {
        path: 'knowledge-graph',
        name: 'KnowledgeGraph',
        component: () => import('@/views/portal/KnowledgeGraph.vue'),
        meta: { title: '医疗知识图谱' }
      },
      // 图像分割模块页面
      {
        path: 'image-segmentation',
        name: 'ImageSegmentation',
        component: () => import('@/views/portal/ImageSegmentation.vue'),
        meta: { title: '图像分割模块' }
      },
      // 患者服务相关路由
      {
        path: 'patient',
        component: () => import('@/views/portal/patient/Layout.vue'),
        children: [
          {
            path: '',
            name: 'PatientServices',
            component: () => import('@/views/portal/patient/PatientServices.vue'),
            meta: { title: '患者服务' }
          },
          {
            path: 'profile',
            name: 'PatientProfile',
            component: () => import('@/views/portal/patient/Profile.vue'),
            meta: { title: '个人中心' }
          },
          {
            path: 'appointment',
            name: 'PatientAppointment',
            component: () => import('@/views/portal/patient/Appointment.vue'),
            meta: { title: '预约挂号' }
          },
          {
            path: 'appointments',
            name: 'PatientAppointmentList',
            component: () => import('@/views/portal/patient/AppointmentList.vue'),
            meta: { title: '我的预约' }
          },
          {
            path: 'records',
            name: 'PatientRecords',
            component: () => import('@/views/portal/patient/Records.vue'),
            meta: { title: '就诊记录' }
          },
          {
            path: 'reports',
            name: 'PatientReports',
            component: () => import('@/views/portal/patient/Reports.vue'),
            meta: { title: '检查报告' }
          },
          {
            path: 'payment',
            name: 'PatientBills',
            component: () => import('@/views/portal/patient/Bills.vue'),
            meta: { title: '费用查询' }
          },
          {
            path: 'prescription',
            name: 'PatientPrescriptions',
            component: () => import('@/views/portal/patient/Prescriptions.vue'),
            meta: { title: '处方查询' }
          }
        ]
      },
      // 医生工作站相关路由
      {
        path: 'doctor',
        redirect: '/portal/doctor/workstation',
        meta: { requireAuth: true, roles: ['doctor'] },
        children: [
          {
            path: 'workstation',
            name: 'DoctorWorkstation',
            component: () => import('@/views/portal/doctor/Workstation.vue'),
            meta: { title: '医生工作站', requireAuth: true, roles: ['doctor'] }
          },
          {
            path: 'profile',
            name: 'DoctorProfile',
            component: () => import('@/views/portal/doctor/Profile.vue'),
            meta: { title: '医生个人中心', requireAuth: true, roles: ['doctor'] }
          },
          {
            path: 'consultation/:id',
            name: 'DoctorConsultation',
            component: () => import('@/views/portal/doctor/Consultation.vue'),
            meta: { title: '患者就诊', requireAuth: true, roles: ['doctor'], activeMenu: '/portal/doctor/workstation' }
          },
          {
            path: 'schedule/:id',
            name: 'DoctorScheduleDetail',
            component: () => import('@/views/portal/doctor/DoctorScheduleDetail.vue'),
            meta: { title: '排班详情', requireAuth: true, roles: ['doctor'], activeMenu: '/portal/doctor/workstation' }
          },
          {
            path: 'medical-record/:id',
            name: 'MedicalRecordDetail',
            component: () => import('@/views/portal/doctor/MedicalRecordDetail.vue'),
            meta: { title: '医疗记录详情', requireAuth: true, roles: ['doctor'], activeMenu: '/portal/doctor/workstation' }
          },
          {
            path: 'prescriptions',
            name: 'DoctorPrescriptions',
            component: () => import('@/views/portal/doctor/DoctorPrescriptions.vue'),
            meta: { title: '关联处方', requireAuth: true, roles: ['doctor'], activeMenu: '/portal/doctor/workstation' }
          },
          {
            path: 'medical-orders',
            name: 'DoctorMedicalOrders',
            component: () => import('@/views/portal/doctor/DoctorMedicalOrders.vue'),
            meta: { title: '关联医嘱', requireAuth: true, roles: ['doctor'], activeMenu: '/portal/doctor/workstation' }
          }
        ]
      },
      // 管理员相关路由
      {
        path: 'admin',
        component: () => import('@/views/portal/patient/Layout.vue'),
        meta: { requireAuth: true, roles: ['admin'] },
        children: [
          {
            path: 'profile',
            name: 'AdminProfile',
            component: () => import('@/views/portal/admin/Profile.vue'),
            meta: { title: '管理员个人中心', requireAuth: true, roles: ['admin'] }
          }
        ]
      },
      {
        path: 'user/profile',
        name: 'UserProfile',
        component: () => import('@/views/portal/user/Profile.vue'),
        meta: { title: '个人中心', requireAuth: true }
      }
    ]
  }
]

// 静态路由（无需权限）
export const constantRoutes = [
  {
    path: '/',
    redirect: '/portal'
  },
  {
    path: '/dashboard',
    component: () => import('@/layout/index.vue'),
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard/index.vue'),
        meta: { title: '首页', icon: 'House' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login/index.vue'),
    meta: { title: '管理员登录', hidden: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register/index.vue'),
    meta: { title: '管理员注册', hidden: true }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue'),
    meta: { title: '404', hidden: true }
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: { title: '403', hidden: true }
  },
  // 添加门户网站路由
  ...portalRoutes
]

// 系统管理路由
const systemRoutes = {
  path: '/system',
  component: () => import('@/layout/index.vue'),
  redirect: '/system/users',
  name: 'System',
  meta: { title: '系统管理', icon: 'Setting', roles: ['admin'] },
  children: [
    {
      path: 'users',
      component: () => import('@/views/system/users/List.vue'),
      name: 'UserList',
      meta: { title: '用户管理', icon: 'User' }
    },
    {
      path: 'users/create',
      component: () => import('@/views/system/users/Form.vue'),
      name: 'UserCreate',
      meta: { title: '新增用户', activeMenu: '/system/users', hidden: true }
    },
    {
      path: 'users/edit/:id',
      component: () => import('@/views/system/users/Form.vue'),
      name: 'UserEdit',
      meta: { title: '编辑用户', activeMenu: '/system/users', hidden: true }
    },
    {
      path: 'roles',
      component: () => import('@/views/system/roles/List.vue'),
      name: 'RoleList',
      meta: { title: '角色管理', icon: 'Lock' }
    },
    {
      path: 'roles/create',
      component: () => import('@/views/system/roles/Form.vue'),
      name: 'RoleCreate',
      meta: { title: '新增角色', activeMenu: '/system/roles', hidden: true }
    },
    {
      path: 'roles/edit/:id',
      component: () => import('@/views/system/roles/Form.vue'),
      name: 'RoleEdit',
      meta: { title: '编辑角色', activeMenu: '/system/roles', hidden: true }
    },
    {
      path: 'departments',
      component: () => import('@/views/system/departments/List.vue'),
      name: 'DepartmentList',
      meta: { title: '科室管理', icon: 'OfficeBuilding' }
    },
    {
      path: 'departments/create',
      component: () => import('@/views/system/departments/Form.vue'),
      name: 'DepartmentCreate',
      meta: { title: '新增科室', activeMenu: '/system/departments', hidden: true }
    },
    {
      path: 'departments/edit/:id',
      component: () => import('@/views/system/departments/Form.vue'),
      name: 'DepartmentEdit',
      meta: { title: '编辑科室', activeMenu: '/system/departments', hidden: true }
    }
  ]
}

// 统计报表路由
const statisticsRoutes = {
  path: '/statistics',
  component: () => import('@/layout/index.vue'),
  redirect: '/statistics/overview',
  name: 'Statistics',
  meta: { title: '统计报表', icon: 'TrendCharts', roles: ['admin', 'manager'] },
  children: [
    {
      path: 'overview',
      component: () => import('@/views/statistics/Overview.vue'),
      name: 'StatisticsOverview',
      meta: { title: '统计概览', icon: 'DataLine' }
    },
    {
      path: 'visits',
      component: () => import('@/views/statistics/VisitStats.vue'),
      name: 'VisitStats',
      meta: { title: '就诊统计', icon: 'User' }
    },
    {
      path: 'income',
      component: () => import('@/views/statistics/IncomeStats.vue'),
      name: 'IncomeStats',
      meta: { title: '收入统计', icon: 'Money' }
    }
  ]
}

// 直接的文件列表路由（单页面路由）
const fileListRoute = {
  path: '/files-list',
  component: () => import('@/layout/index.vue'),
  children: [
    {
      path: '',
      name: 'FileListPage',
      component: () => import('@/views/files/List.vue'),
      meta: { 
        title: '文件列表', 
        icon: 'Document',
        permissions: ['file:read']
      }
    }
  ]
}

// 动态路由（需要根据权限动态添加）
export const asyncRoutes = [
  // 患者管理
  {
    path: '/patients',
    component: () => import('@/layout/index.vue'),
    redirect: '/patients/list',
    meta: { 
      title: '患者管理',
      icon: 'User',
      permissions: ['patient:read']
    },
    children: [
      {
        path: 'list',
        name: 'PatientList',
        component: () => import('@/views/patients/List.vue'),
        meta: { 
          title: '患者列表',
          permissions: ['patient:read']
        }
      },
      {
        path: 'create',
        name: 'PatientCreate',
        component: () => import('@/views/patients/Form.vue'),
        meta: { 
          title: '新增患者',
          permissions: ['patient:create']
        }
      },
      {
        path: 'edit/:id',
        name: 'PatientEdit',
        component: () => import('@/views/patients/Form.vue'),
        meta: { 
          title: '编辑患者',
          permissions: ['patient:update'],
          activeMenu: '/patients/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'PatientDetail',
        component: () => import('@/views/patients/Detail.vue'),
        meta: { 
          title: '患者详情',
          permissions: ['patient:read'],
          activeMenu: '/patients/list',
          hidden: true
        }
      }
    ]
  },
  // 医疗记录管理
  {
    path: '/medical-records',
    component: () => import('@/layout/index.vue'),
    redirect: '/medical-records/list',
    meta: { 
      title: '医疗记录',
      icon: 'Document',
      permissions: ['medical_record:read'],
      roles: ['admin', 'doctor', 'nurse']
    },
    children: [
      {
        path: 'list',
        name: 'MedicalRecordList',
        component: () => import('@/views/medical-records/List.vue'),
        meta: { 
          title: '病历列表',
          permissions: ['medical_record:read']
        }
      },
      {
        path: 'create',
        name: 'MedicalRecordCreate',
        component: () => import('@/views/medical-records/Form.vue'),
        meta: { 
          title: '新增病历',
          permissions: ['medical_record:create'],
          roles: ['admin', 'doctor']
        }
      },
      {
        path: 'edit/:id',
        name: 'MedicalRecordEdit',
        component: () => import('@/views/medical-records/Form.vue'),
        meta: { 
          title: '编辑病历',
          permissions: ['medical_record:update'],
          roles: ['admin', 'doctor'],
          activeMenu: '/medical-records/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'MedicalRecordDetail',
        component: () => import('@/views/medical-records/Detail.vue'),
        meta: { 
          title: '病历详情',
          permissions: ['medical_record:read'],
          activeMenu: '/medical-records/list',
          hidden: true
        }
      }
    ]
  },
  // 处方管理
  {
    path: '/prescriptions',
    component: () => import('@/layout/index.vue'),
    redirect: '/prescriptions/list',
    meta: { 
      title: '处方管理',
      icon: 'List',
      permissions: ['prescription:read'],
      roles: ['admin', 'doctor', 'pharmacist', 'nurse']
    },
    children: [
      {
        path: 'list',
        name: 'PrescriptionList',
        component: () => import('@/views/prescriptions/List.vue'),
        meta: { 
          title: '处方列表',
          permissions: ['prescription:read']
        }
      },
      {
        path: 'create',
        name: 'PrescriptionCreate',
        component: () => import('@/views/prescriptions/Form.vue'),
        meta: { 
          title: '新增处方',
          permissions: ['prescription:create'],
          roles: ['admin', 'doctor']
        }
      },
      {
        path: 'edit/:id',
        name: 'PrescriptionEdit',
        component: () => import('@/views/prescriptions/Form.vue'),
        meta: { 
          title: '编辑处方',
          permissions: ['prescription:update'],
          roles: ['admin', 'doctor'],
          activeMenu: '/prescriptions/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'PrescriptionDetail',
        component: () => import('@/views/prescriptions/Detail.vue'),
        meta: { 
          title: '处方详情',
          permissions: ['prescription:read'],
          activeMenu: '/prescriptions/list',
          hidden: true
        }
      },
      {
        path: 'print/:id',
        name: 'PrescriptionPrint',
        component: () => import('@/views/prescriptions/Print.vue'),
        meta: { 
          title: '打印处方',
          permissions: ['prescription:print'],
          roles: ['admin', 'doctor', 'pharmacist'],
          activeMenu: '/prescriptions/list',
          hidden: true
        }
      }
    ]
  },
  
  // 医嘱管理
  {
    path: '/medical-orders',
    component: () => import('@/layout/index.vue'),
    redirect: '/medical-orders/list',
    meta: { 
      title: '医嘱管理',
      icon: 'Notebook',
      permissions: ['medical_order:read']
    },
    children: [
      {
        path: 'list',
        name: 'MedicalOrderList',
        component: () => import('@/views/medical-orders/List.vue'),
        meta: { 
          title: '医嘱列表',
          permissions: ['medical_order:read']
        }
      },
      {
        path: 'create',
        name: 'MedicalOrderCreate',
        component: () => import('@/views/medical-orders/Form.vue'),
        meta: { 
          title: '新增医嘱',
          permissions: ['medical_order:create']
        }
      },
      {
        path: 'edit/:id',
        name: 'MedicalOrderEdit',
        component: () => import('@/views/medical-orders/Form.vue'),
        meta: { 
          title: '编辑医嘱',
          permissions: ['medical_order:update'],
          activeMenu: '/medical-orders/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'MedicalOrderDetail',
        component: () => import('@/views/medical-orders/Detail.vue'),
        meta: { 
          title: '医嘱详情',
          permissions: ['medical_order:read'],
          activeMenu: '/medical-orders/list',
          hidden: true
        }
      }
    ]
  },
  
  // 支付管理
  {
    path: '/payments',
    component: () => import('@/layout/index.vue'),
    redirect: '/payments/list',
    meta: { 
      title: '支付管理',
      icon: 'Money',
      permissions: ['payment:read'],
      roles: ['admin', 'receptionist']
    },
    children: [
      {
        path: 'list',
        name: 'PaymentList',
        component: () => import('@/views/payments/List.vue'),
        meta: { 
          title: '支付列表',
          permissions: ['payment:read']
        }
      },
      {
        path: 'create',
        name: 'PaymentCreate',
        component: () => import('@/views/payments/Form.vue'),
        meta: { 
          title: '新增支付',
          permissions: ['payment:create'],
          roles: ['admin', 'receptionist']
        }
      },
      {
        path: 'detail/:id',
        name: 'PaymentDetail',
        component: () => import('@/views/payments/Detail.vue'),
        meta: { 
          title: '支付详情',
          permissions: ['payment:read'],
          activeMenu: '/payments/list',
          hidden: true
        }
      }
    ]
  },
  
  // 医生管理
  {
    path: '/doctors',
    component: () => import('@/layout/index.vue'),
    redirect: '/doctors/list',
    meta: { 
      title: '医生管理',
      icon: 'Avatar',
      permissions: ['doctor:read']
    },
    children: [
      {
        path: 'list',
        name: 'DoctorList',
        component: () => import('@/views/doctors/List.vue'),
        meta: { 
          title: '医生列表',
          permissions: ['doctor:read']
        }
      },
      {
        path: 'create',
        name: 'DoctorCreate',
        component: () => import('@/views/doctors/Form.vue'),
        meta: { 
          title: '新增医生',
          permissions: ['doctor:create']
        }
      },
      {
        path: 'edit/:id',
        name: 'DoctorEdit',
        component: () => import('@/views/doctors/Form.vue'),
        meta: { 
          title: '编辑医生',
          permissions: ['doctor:update'],
          activeMenu: '/doctors/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'DoctorDetail',
        component: () => import('@/views/doctors/Detail.vue'),
        meta: { 
          title: '医生详情',
          permissions: ['doctor:read'],
          activeMenu: '/doctors/list',
          hidden: true
        }
      }
    ]
  },
  // 预约管理
  {
    path: '/appointments',
    component: () => import('@/layout/index.vue'),
    redirect: '/appointments/list',
    meta: { 
      title: '预约管理',
      icon: 'Calendar',
      permissions: ['appointment:read'],
      roles: ['admin', 'doctor', 'nurse', 'receptionist', 'patient']
    },
    children: [
      {
        path: 'list',
        name: 'AppointmentList',
        component: () => import('@/views/appointments/List.vue'),
        meta: { 
          title: '预约列表',
          permissions: ['appointment:read']
        }
      },
      {
        path: 'create',
        name: 'AppointmentCreate',
        component: () => import('@/views/appointments/Form.vue'),
        meta: { 
          title: '新增预约',
          permissions: ['appointment:create'],
          roles: ['admin', 'receptionist', 'patient']
        }
      },
      {
        path: 'edit/:id',
        name: 'AppointmentEdit',
        component: () => import('@/views/appointments/Form.vue'),
        meta: { 
          title: '编辑预约',
          permissions: ['appointment:update'],
          roles: ['admin', 'receptionist'],
          activeMenu: '/appointments/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'AppointmentDetail',
        component: () => import('@/views/appointments/Detail.vue'),
        meta: { 
          title: '预约详情',
          permissions: ['appointment:read'],
          activeMenu: '/appointments/list',
          hidden: true
        }
      }
    ]
  },
  // 排班管理
  {
    path: '/schedules',
    component: () => import('@/layout/index.vue'),
    redirect: '/schedules/list',
    meta: { 
      title: '排班管理',
      icon: 'Stopwatch',
      permissions: ['schedule:read']
    },
    children: [
      {
        path: 'list',
        name: 'ScheduleList',
        component: () => import('@/views/schedules/List.vue'),
        meta: { 
          title: '排班列表',
          permissions: ['schedule:read']
        }
      },
      {
        path: 'create',
        name: 'ScheduleCreate',
        component: () => import('@/views/schedules/Form.vue'),
        meta: { 
          title: '新增排班',
          permissions: ['schedule:create']
        }
      },
      {
        path: 'batch',
        name: 'ScheduleBatch',
        component: () => import('@/views/schedules/Batch.vue'),
        meta: { 
          title: '批量排班',
          permissions: ['schedule:create']
        }
      },
      {
        path: 'detail/:id',
        name: 'ScheduleDetail',
        component: () => import('@/views/schedules/Detail.vue'),
        meta: { 
          title: '排班详情',
          permissions: ['schedule:read']
        }
      }
    ]
  },
  // 药品管理
  {
    path: '/drugs',
    component: () => import('@/layout/index.vue'),
    redirect: '/drugs/list',
    meta: { 
      title: '药品管理',
      icon: 'FirstAidKit',
      permissions: ['drug:read'],
      roles: ['admin', 'pharmacist', 'doctor']
    },
    children: [
      {
        path: 'list',
        name: 'DrugList',
        component: () => import('@/views/drugs/List.vue'),
        meta: { 
          title: '药品列表',
          permissions: ['drug:read']
        }
      },
      {
        path: 'create',
        name: 'DrugCreate',
        component: () => import('@/views/drugs/Form.vue'),
        alias: 'add',
        meta: { 
          title: '新增药品',
          permissions: ['drug:create'],
          roles: ['admin', 'pharmacist']
        }
      },
      {
        path: 'edit/:id',
        name: 'DrugEdit',
        component: () => import('@/views/drugs/Form.vue'),
        meta: { 
          title: '编辑药品',
          permissions: ['drug:update'],
          roles: ['admin', 'pharmacist'],
          activeMenu: '/drugs/list',
          hidden: true
        }
      },
      {
        path: 'detail/:id',
        name: 'DrugDetail',
        component: () => import('@/views/drugs/Detail.vue'),
        meta: { 
          title: '药品详情',
          permissions: ['drug:read'],
          activeMenu: '/drugs/list',
          hidden: true
        }
      },
      {
        path: 'inventory',
        name: 'DrugInventory',
        component: () => import('@/views/drugs/Inventory.vue'),
        meta: { 
          title: '药品库存',
          permissions: ['drug_inventory:read'],
          roles: ['admin', 'pharmacist']
        }
      },
      {
        path: 'inventory/add',
        name: 'DrugInventoryAdd',
        component: () => import('@/views/drugs/InventoryAdd.vue'),
        meta: { 
          title: '入库管理',
          permissions: ['drug_inventory:create'],
          roles: ['admin', 'pharmacist']
        }
      },
      {
        path: 'inventory/expiring',
        name: 'DrugInventoryExpiring',
        component: () => import('@/views/drugs/InventoryExpiring.vue'),
        meta: { 
          title: '药品效期',
          permissions: ['drug_inventory:read'],
          roles: ['admin', 'pharmacist']
        }
      },
      {
        path: 'inventory/detail/:id',
        name: 'DrugInventoryDetail',
        component: () => import('@/views/drugs/InventoryDetail.vue'),
        meta: { 
          title: '库存详情',
          permissions: ['drug_inventory:read'],
          roles: ['admin', 'pharmacist'],
          activeMenu: '/drugs/inventory',
          hidden: true
        }
      }
    ]
  },
  // 添加系统管理和统计报表路由
  systemRoutes,
  statisticsRoutes,
  
  // 直接的文件列表路由（单页面路由）
  fileListRoute,
  
  // 匹配任意路径并重定向到404
  { 
    path: '/:pathMatch(.*)*', 
    redirect: '/404', 
    meta: { hidden: true } 
  }
]

// 创建路由
const router = createRouter({
  history: createWebHistory(),
  routes: [...constantRoutes, ...asyncRoutes, statisticsRoutes, systemRoutes], // 一次性注册所有路由
  scrollBehavior(to, from, savedPosition) {
    // 如果有保存的位置，则返回到保存的位置
    if (savedPosition) {
      return savedPosition
    }
    // 否则滚动到顶部
    return { top: 0 }
  }
})

// 添加全局加载状态
let isLoadingUserInfo = false

// 配置进度条
NProgress.configure({ showSpinner: false })

// 白名单
const whiteList = ['/login', '/register', '/404', '/403', '/portal/login', '/portal/register']

// 路由全局前置守卫
router.beforeEach(async(to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 医疗信息系统` : '医疗信息系统'
  
  const userStore = useUserStore()
  
  // 判断是否已登录
  if (userStore.isLoggedIn) {
    if (to.path === '/login' || to.path === '/register' || to.path === '/portal/login' || to.path === '/portal/register') {
      // 如果已登录但访问登录页，则根据角色重定向
      if (userStore.userRole === 'admin') {
        next({ path: '/dashboard' })
      } else {
        next({ path: '/portal' })
      }
      NProgress.done()
    } else {
      // 判断是否已获取用户信息
      if (Object.keys(userStore.userInfo).length === 0) {
        // 如果正在加载用户信息，等待加载完成
        if (isLoadingUserInfo) {
          // 等待用户信息加载完成
          const checkUserInfo = () => {
            return new Promise((resolve) => {
              const timer = setInterval(() => {
                if (!isLoadingUserInfo && Object.keys(userStore.userInfo).length > 0) {
                  clearInterval(timer)
                  resolve()
                } else if (!isLoadingUserInfo && !userStore.isLoggedIn) {
                  // 如果加载失败并且已经logout
                  clearInterval(timer)
                  resolve()
                }
              }, 100)
            })
          }
          
          await checkUserInfo()
          
          // 重新检查登录状态
          if (!userStore.isLoggedIn) {
            next({ path: '/portal/login', query: { redirect: to.fullPath } })
            NProgress.done()
            return
          }
        } else {
          // 设置加载状态并获取用户信息
          isLoadingUserInfo = true
        try {
          // 获取用户信息
          await userStore.fetchUserInfo()
            isLoadingUserInfo = false
          
          // 检查用户角色是否有权限访问
          if (to.meta.roles && to.meta.roles.length > 0) {
            if (!to.meta.roles.includes(userStore.userRole)) {
              next({ path: '/403' })
              NProgress.done()
              return
            }
          }
          
          next({ ...to, replace: true })
            return
        } catch (error) {
          console.error('获取用户信息失败:', error)
            isLoadingUserInfo = false
          // 出错则登出并重定向到登录页
          userStore.logout()
          next({ path: '/portal/login', query: { redirect: to.fullPath } })
          NProgress.done()
            return
          }
        }
      }
      
      // 已有用户信息，进行权限检查
        if (to.meta.requireAuth && !userStore.isLoggedIn) {
          // 未登录，跳转到登录页
          next({ path: '/portal/login', query: { redirect: to.fullPath } })
          NProgress.done()
        } else if (to.meta.roles && to.meta.roles.length > 0) {
          // 检查用户角色
          if (!to.meta.roles.includes(userStore.userRole)) {
            next({ path: '/403' })
            NProgress.done()
          } else {
            next()
          }
        } else {
          next()
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path) || to.path.startsWith('/portal') && !to.meta.requireAuth) {
      // 在白名单内或公开的门户页面，直接访问
      next()
    } else {
      // 其他需要登录的页面，重定向到登录页
      next({ path: '/portal/login', query: { redirect: to.fullPath } })
      NProgress.done()
    }
  }
})

// 路由全局后置守卫
router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router 